<template>
  <view class="page-container">
    <!-- 顶部搜索框区域 -->
    <view class="search-wrapper">
      <view class="search-container" ref="searchContainerRef">
        <view class="search-input-wrapper">
          <view class="search-icon">🔍</view>
          <input class="search-input" placeholder="搜索设备名称" v-model="searchKeyword" @input="handleSearch"
            @focus="handleFocus" @blur="hideResults" :focus="isInputFocused" />
          <view class="clear-icon" v-if="searchKeyword" @click.stop="clearSearch">×</view>
        </view>
      </view>

      <!-- 过滤出来的点位下拉选项 -->
      <view class="dropdown-container" v-if="showResults">
        <!-- 下拉框关闭按钮 -->
        <view class="dropdown-close-btn" @click.stop="closeDropdown">×</view>

        <view class="search-results" v-if="filteredPoints.length > 0">
          <view class="result-item" v-for="(item, index) in filteredPoints" :key="index" @click="selectPoint(item)">
            <view class="result-name">{{ item.deviceName.length > 6 ? item.deviceName.slice(0, 6) + '...' :
              item.deviceName }}</view>
            <view class="result-id">ID: {{ item.id }}</view>
            <view class="result-status" :class="item.online ? 'status-online' : 'status-offline'">
              {{ item.online ? '在线' : '休眠' }}
            </view>
          </view>
        </view>

        <!-- 无结果提示 -->
        <view class="no-results" v-if="filteredPoints.length === 0 && searchKeyword">
          未找到匹配的点位
        </view>
      </view>
    </view>

    <!-- 中间地图区域 -->
    <view class="map-container">
      <map :latitude="currentLatitude" :longitude="currentLongitude" :markers="filteredMarkers" :scale="scale"
        style="width:100%;height:100%" @markertap="handleMarkerClick" />
    </view>

    <!-- 底部信息卡片 -->
    <view class="info-card" v-if="showInfoCard">
      <!-- 信息框关闭按钮（修复显示问题） -->
      <view class="info-card-close-btn" @click="closeInfoCard">×</view>

      <view class="card-wrapper">
        <view class="card-image">
          <image mode="widthFix" src="@/static/device.png" class="device-img"></image>
        </view>

        <view class="card-info">
          <view class="card-header">
            <view class="device-title">{{ (markerSelect && markerSelect.deviceName) ? markerSelect.deviceName.length > 4 ? markerSelect.deviceName.slice(0,4) + '...' : markerSelect.deviceName : '请选择设备' }}</view>
            <view class="device-status" :class="markerSelect?.online ? 'status-online' : 'status-offline'">
              {{ markerSelect?.online ? '在线' : '休眠' }}
            </view>
          </view>

          <view class="card-body">
            <view class="info-grid">
              <view class="info-item">
                <view class="item-label">水权量：</view>
                <view class="item-value">{{ liveDate['定量值'].value || 0 }}{{ liveDate['定量值'].unit }}</view>
              </view>
              <view class="info-item">
                <view class="item-label">累计流量：</view>
                <view class="item-value">{{ liveDate['正向累积'].value || 0 }}{{ liveDate['正向累积'].unit }}</view>
              </view>
              <view class="info-item">
                <view class="item-label">瞬时流量：</view>
                <view class="item-value">{{ liveDate['瞬时流量'].value || 0 }}{{ 
                  liveDate['瞬时流量'].unit  }}</view>
              </view>
              <view class="info-item coordinate-item">
                <view class="item-label">坐标：</view>
                <view class="item-value">
                  <view class="coordinate-text">
                    {{ markerSelect?.latitude ? markerSelect.latitude.toFixed(3) : '暂无' }},
                    {{ markerSelect?.longitude ? markerSelect.longitude.toFixed(3) : '暂无' }}
                  </view>
                </view>
              </view>
            </view>

            <view class="card-actions">
              <button class="detail-btn" @click="detailbyID" :disabled="!markerSelect">
                查看详情
              </button>
              <button class="navigate-btn" @click="handleNavigateClick(markerSelect)" :disabled="!markerSelect?.latitude">
                导航前往
              </button>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed, nextTick } from 'vue';
import { devicemapApi, ddevicePageApi, lastdpbyIdApi } from "@/axios/pageApi/device"

// 搜索相关状态
const searchKeyword = ref('');
const filteredPoints = ref([]);
const showResults = ref(false);
const isInputFocused = ref(false);
const searchContainerRef = ref(null);
const scale = ref(13)
// 新增：下拉框关闭方法
const closeDropdown = () => {
  showResults.value = false;
  isInputFocused.value = false;
};

// 假数据池
const mockPoints = [
  { id: 'EQ001', deviceName: '农业灌溉设备-东区1号', online: 1, latitude: 39.914, longitude: 116.417, imei: '861234567890123' },
  { id: 'EQ002', deviceName: '工业用水监测器-A组', online: 1, latitude: 39.924, longitude: 116.427, imei: '861234567890124' },
  { id: 'EQ003', deviceName: '生活用水计量表-小区1', online: 0, latitude: 39.894, longitude: 116.397, imei: '861234567890125' },
  { id: 'EQ004', deviceName: '智能水表-商业区', online: 1, latitude: 39.934, longitude: 116.407, imei: '861234567890126' },
  { id: 'EQ005', deviceName: '农业灌溉设备-西区2号', online: 1, latitude: 39.884, longitude: 116.437, imei: '861234567890127' },
  { id: 'EQ006', deviceName: '工业用水监测器-B组', online: 0, latitude: 39.904, longitude: 116.447, imei: '861234567890128' },
  { id: 'EQ007', deviceName: '生活用水计量表-小区2', online: 1, latitude: 39.914, longitude: 116.387, imei: '861234567890129' },
];

// 地图核心：默认经纬度
const currentLatitude = ref(39.9042); // 默认纬度（北京）
const currentLongitude = ref(116.4074); // 默认经度（北京）

// 地图状态
const allMarkers = ref([]);
const markerSelect = ref({})
const liveDate = ref({
  '定量值': { value: '', unit: '' },
  '正向累积': { value: '', unit: '' },
  '瞬时流量': { value: '', unit: '' }
})
const showInfoCard = ref(false); // 用于控制信息框显示/隐藏
const props = defineProps(["isMappage", "latitude", "longitude", "selectMarker"]);

// 标记点处理
const filteredMarkers = computed(() => {
  return allMarkers.value.map(marker => ({
    id: marker.id || `auto-${Date.now()}`,
    latitude: marker.latitude || currentLatitude.value,
    longitude: marker.longitude || currentLongitude.value,
    iconPath: marker.online == 1 ? '/static/map/online.png' : '/static/map/offline.png',
    width: 30,
    height: 30
  }));
});

// 搜索处理
const handleSearch = (e) => {
  const value = e.target?.value || e.detail?.value || '';
  const keyword = value.trim().toLowerCase();

  if (!keyword) {
    filteredPoints.value = [];
    return;
  }
  let obj = {
    current: 1,
    size: 10,
    deviceName: e.detail.value,
    online: '',

  }
  ddevicePageApi(obj).then(res => {
    filteredPoints.value = res.data.records
  })
  showResults.value = true;
};

// 选择点位
const selectPoint = (point) => {
  markerSelect.value = { ...point };
  searchKeyword.value = point.deviceName;
  showResults.value = false;
  loadMarkerData(point);
  showInfoCard.value = true;

  // 移动地图中心到选中点位
  currentLatitude.value = point.latitude;
  currentLongitude.value = point.longitude;
  
};

// 关闭信息框
const closeInfoCard = () => {
  showInfoCard.value = false;
  nextTick(() => {
    markerSelect.value = {};
    liveDate.value = {
      '定量值': { value: '', unit: '' },
      '正向累积': { value: '', unit: '' },
      '瞬时流量': { value: '', unit: '' }
    };
  });
};

// 输入框交互
const handleFocus = () => {
  isInputFocused.value = true;
  if (searchKeyword.value) {
    handleSearch({ target: { value: searchKeyword.value } });
  } else {
    filteredPoints.value = [];
    showResults.value = true;
  }
};

const hideResults = () => {
  setTimeout(() => {
    showResults.value = false;
  }, 200);
};

const clearSearch = () => {
  searchKeyword.value = '';
  filteredPoints.value = [];
  showResults.value = false;
};

// 初始化地图数据
onMounted(async () => {
  // 若有传入的初始坐标，优先使用
  if (props.latitude && props.longitude) {
    currentLatitude.value = props.latitude;
    currentLongitude.value = props.longitude;
  }

  try {
    // 加载真实点位数据
    const res = await devicemapApi();
    let markerArr = res.data;
    let pointArr = markerArr.map(item => item.proList);
    // 合并数组
    let mergedArray = pointArr.reduce((acc, curr) => acc.concat(curr), [])
      .map(item => item.deviceList)
      .reduce((acc, curr) => acc.concat(curr), []);

    // 处理真实数据
    console.log(mergedArray,'=====');
    allMarkers.value = mergedArray.map(marker => ({
      
      id: marker.id || `auto-${Date.now()}`,
      deviceName: marker.deviceName || '未知设备',
      online: marker.online ?? 0,
      latitude: marker.latitude ?? currentLatitude.value,
      longitude: marker.longitude ?? currentLongitude.value,
      gcjLatitude: marker.gcjLatitude,
      gcjLongitude: marker.gcjLongitude,
      imei: marker.imei || ''
    }));

    // // 处理默认选中点位
    // if (props.selectMarker) {
    //   markerSelect.value = props.selectMarker;
    //   loadMarkerData(props.selectMarker);
    //   showInfoCard.value = true;
    //   currentLatitude.value = props.selectMarker.latitude ?? currentLatitude.value;
    //   currentLongitude.value = props.selectMarker.longitude ?? currentLongitude.value;
    // }
  } catch (e) {
    console.error('加载地图数据失败:', e);
    // 失败时使用假数据
    allMarkers.value = mockPoints;
  }
});

// 加载设备数据
async function loadMarkerData(marker) {
  // 重置数据结构
  liveDate.value = {
    '定量值': { value: '', unit: '' },
    '正向累积': { value: '', unit: '' },
    '瞬时流量': { value: '', unit: '' }
  };

  let res = await lastdpbyIdApi(marker.imei)
  console.log('res=========', res);
  let dpsdata = res.data.devs[0].dps
  dpsdata.forEach(item => {
    liveDate.value[item.title] = { value: item.value, unit: item.unit }
  });
  
}


// 地图标记点点击事件
const handleMarkerClick = (e) => {
  if (props.isMappage) {
    const matchedMarker = allMarkers.value.find(m => m.id === e.detail.markerId);
    if (matchedMarker) {
      markerSelect.value = { ...matchedMarker };
      console.log('markerSelect===========>', markerSelect.value);

      loadMarkerData(matchedMarker);
      showInfoCard.value = true;
      // 移动地图中心
      currentLatitude.value = matchedMarker.latitude;
      currentLongitude.value = matchedMarker.longitude;
      scale.value = 18
    } else {
      closeInfoCard();
    }
  }
};

// 导航函数
function navigateToDevice() {
  if (markerSelect.value?.latitude) {
    uni.openLocation({
      latitude: markerSelect.value.latitude,
      longitude: markerSelect.value.longitude,
      name: markerSelect.value.deviceName,
      scale: 18
    });
  }
}

// 详情页跳转
function detailbyID() {
  if (markerSelect.value) {
    uni.navigateTo({
      url: `/pages/detailsPage/detailsPage?name=${markerSelect.value.id}`,
    });
  }
}

// 错误提示
function showErrorToast(message) {
  uni.showToast({
    title: message,
    icon: 'none',
    duration: 2000
  });
}

//高德地图引入
// 优化的环境检测模块（解决APP被误判为小程序的问题）
function detectEnvironment() {
  return new Promise(resolve => {
    const env = {
      platform: 'unknown',
      isH5: false,
      isWechat: false,
      isMiniProgram: false,
      isApp: false,
      framework: 'unknown' // 新增：识别框架类型
    };

    // 1. 优先检测Uni-app原生APP环境
    if (typeof plus !== 'undefined') {
      // plus是5+Runtime的核心对象，仅在Uni-app/5+ App中存在
      env.isApp = true;
      env.framework = 'uni-app';
      
      // 检测平台类型
      if (plus.os.name.toLowerCase() === 'android') {
        env.platform = 'android';
      } else if (plus.os.name.toLowerCase() === 'ios') {
        env.platform = 'ios';
      }
      
      console.log('检测到Uni-app原生APP环境:', env);
      resolve(env);
      return;
    }

    // 2. 检测微信小程序环境
    if (typeof wx !== 'undefined' && wx.getSystemInfo && wx.getSystemInfoSync) {
      // 小程序环境中存在wx对象且有特定方法
      // 进一步验证小程序特有API
      if (typeof wx.createCanvasContext !== 'undefined' || 
          typeof wx.getLaunchOptionsSync !== 'undefined') {
        env.isMiniProgram = true;
        env.framework = 'wechat-miniprogram';
        
        try {
          const sysInfo = wx.getSystemInfoSync();
          env.platform = sysInfo.platform;
        } catch (e) {
          console.warn('获取小程序系统信息失败:', e);
        }
        
        console.log('检测到微信小程序环境:', env);
        resolve(env);
        return;
      }
    }

    // 3. 检测H5环境
    if (typeof window !== 'undefined' && typeof document !== 'undefined') {
      env.isH5 = true;
      env.framework = 'h5';
      const userAgent = window.navigator.userAgent.toLowerCase();
      
      // 检测微信浏览器
      env.isWechat = userAgent.includes('micromessenger');
      
      // 检测平台
      if (userAgent.includes('android')) {
        env.platform = 'android';
      } else if (userAgent.includes('iphone') || userAgent.includes('ios')) {
        env.platform = 'ios';
      }
      
      console.log('检测到H5环境:', env);
      resolve(env);
      return;
    }

    // 4. 其他未知环境
    console.log('检测到未知环境:', env);
    resolve(env);
  });
}

// 修复的导航主函数（使用优化后的环境检测）
function navigateWithAmap(latitude, longitude, name) {
  console.log('===== 开始导航流程 =====');
  console.log('原始参数:', { latitude, longitude, name });

  // 参数验证
  if (!validateLocation(latitude, longitude)) {
    showToast('位置信息无效，无法导航');
    return;
  }

  // 标准化参数
  const lat = Number(latitude).toFixed(6);
  const lon = Number(longitude).toFixed(6);
  const locationName = encodeURIComponent(name || '设备位置');
  console.log('标准化参数:', { lat, lon, locationName });

  // 构建导航链接
  const schemes = {
    android: `androidamap://navi?sourceApplication=amap&lat=${lat}&lon=${lon}&dev=0&style=2&poiname=${locationName}`,
    ios: `iosamap://navi?sourceApplication=amap&lat=${lat}&lon=${lon}&dev=0&style=2&poiname=${locationName}`,
    web: `https://uri.amap.com/navigation?to=${lat},${lon},${locationName}&mode=car&src=amap`
  };
  console.log('生成的导航链接:', schemes);

  // 使用优化后的环境检测
  detectEnvironment().then(env => {
    console.log('当前环境检测结果:', env);
    
    // 根据环境执行策略
    if (env.isApp) {
      // 原生APP环境（优先处理）
      handleAppEnvironment(env.platform, schemes);
    } else if (env.isMiniProgram) {
      // 小程序环境
      handleMiniProgramEnvironment(schemes.web);
    } else if (env.isH5) {
      // H5环境
      handleH5Environment(schemes);
    } else {
      // 未知环境
      showModal({
        title: '环境错误',
        content: '无法识别当前运行环境',
        confirmText: '使用网页版导航',
        success: (res) => {
          if (res.confirm) {
            openUrl(schemes.web);
          }
        }
      });
    }
  }).catch(err => {
    console.error('环境检测失败:', err);
    showToast('无法检测当前环境');
  });
}

// APP环境处理函数（增强版）
function handleAppEnvironment(platform, schemes) {
  console.log(`处理${platform}原生APP环境导航`);
  
  if (!schemes[platform]) {
    showToast(`不支持${platform}平台导航`);
    return;
  }

  // 对于Uni-app原生APP，使用plus.runtime.openURL更可靠
  if (typeof plus !== 'undefined' && plus.runtime && plus.runtime.openURL) {
    console.log('使用plus.runtime.openURL调用导航');
    
    plus.runtime.openURL(schemes[platform], 
      function(success) {
        console.log('导航调用成功:', success);
        if(success.includes('No Activity found to handle Intent')){
          showDownloadConfirm(schemes.web);
        }
      },
      function(error) {
        console.error('导航调用失败:', error);
        showDownloadConfirm(schemes.web);
      }
    );
  } else {
    // 备选方案
    openMapSchema(schemes[platform])
      .then(() => console.log(`${platform}环境调用成功`))
      .catch(err => {
        console.error(`${platform}环境调用失败`, err);
        showDownloadConfirm(schemes.web);
      });
  }
}

// 其他辅助函数保持不变（validateLocation, openMapSchema等）

function validateLocation(lat, lon) {
  console.log(lat, lon,'lat, lon');
  if (!lat || !lon) {
    console.error('经纬度不能为空');
    return false;
  }
  
  const latitude = Number(lat);
  const longitude = Number(lon);
  
  if (latitude < -90 || latitude > 90 || longitude < -180 || longitude > 180) {
    console.error('经纬度超出有效范围', { latitude, longitude });
    return false;
  }
  
  if (isNaN(latitude) || isNaN(longitude)) {
    console.error('经纬度不是有效数字', { lat, lon });
    return false;
  }
  
  return true;
}

function openMapSchema(url) {
  return new Promise((resolve, reject) => {
    if (!url) {
      reject(new Error('导航链接为空'));
      return;
    }

    console.log('尝试打开链接:', url);
    const startTime = Date.now();
    const timeout = 3000;

    const timeoutTimer = setTimeout(() => {
      reject(new Error(`打开链接超时（${timeout}ms）`));
    }, timeout);

    if (typeof uni !== 'undefined' && typeof uni.openURL === 'function') {
      uni.openURL({
        url: url,
        success: () => {
          clearTimeout(timeoutTimer);
          resolve();
        },
        fail: (err) => {
          clearTimeout(timeoutTimer);
          reject(err);
        }
      });
    } else if (typeof window !== 'undefined') {
      window.location.href = url;
      setTimeout(() => {
        const endTime = Date.now();
        clearTimeout(timeoutTimer);
        
        if (endTime - startTime < 2000) {
          reject(new Error('浏览器未响应跳转'));
        } else {
          resolve();
        }
      }, 1000);
    } else {
      clearTimeout(timeoutTimer);
      reject(new Error('不支持的打开方式'));
    }
  });
}

function openUrl(url) {
  if (!url) return;
  
  console.log('打开链接:', url);
  if (typeof plus !== 'undefined' && plus.runtime && plus.runtime.openURL) {
    plus.runtime.openURL(url);
  } else if (typeof uni !== 'undefined' && uni.openURL) {
    uni.openURL({ url });
  } else if (typeof wx !== 'undefined' && wx.openURL) {
    wx.openURL({ url });
  } else if (typeof window !== 'undefined') {
    window.open(url, '_blank');
  }
}

function showDownloadConfirm(webUrl) {
  showModal({
    title: '无法打开高德地图',
    content: '未检测到高德地图应用，是否下载或使用网页版导航？',
    confirmText: '下载高德地图',
    cancelText: '网页版导航',
    success: (res) => {
      if (res.confirm) {
        openUrl('https://mobile.amap.com/');
      } else if (res.cancel) {
        openUrl(webUrl);
      }
    }
  });
}

function showModal(options) {
  if (typeof uni !== 'undefined' && uni.showModal) {
    uni.showModal(options);
  } else if (typeof wx !== 'undefined' && wx.showModal) {
    wx.showModal(options);
  } else if (typeof window !== 'undefined') {
    if (confirm(`${options.title}\n${options.content}\n点击确定表示"${options.confirmText}"，取消表示"${options.cancelText}"`)) {
      options.success?.({ confirm: true });
    } else {
      options.success?.({ confirm: false, cancel: true });
    }
  }
}

function showToast(title) {
  if (typeof uni !== 'undefined' && uni.showToast) {
    uni.showToast({ title, icon: 'none', duration: 2500 });
  } else if (typeof wx !== 'undefined' && wx.showToast) {
    wx.showToast({ title, icon: 'none', duration: 2500 });
  } else if (typeof window !== 'undefined') {
    alert(title);
  }
}

function handleNavigateClick(marker) {
  console.log('导航按钮点击事件触发:', marker);
  if (!marker) {
    showToast('请先选择一个设备');
    return;
  }
  navigateWithAmap(marker.gcjLatitude, marker.gcjLongitude, marker.deviceName);
}


</script>
<style scoped>
/* 页面容器使用flex布局 */
.page-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  width: 100%;
  background-color: #f5f5f5;
}

/* 搜索区域外层容器 */
.search-wrapper {
  position: relative;
  z-index: 100;
  width: 100%;
  box-sizing: border-box;
  padding: 15rpx 20rpx;
  background-color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

/* 顶部搜索框样式 */
.search-container {
  width: 100%;
  box-sizing: border-box;
}

/* 下拉框容器 */
.dropdown-container {
  width: 100%;
  margin-top: 8rpx;
  position: relative;
  z-index: 101;
}

/* 下拉框关闭按钮 - 新增样式 */
.dropdown-close-btn {
  position: absolute;
  top: 15rpx;
  right: 15rpx;
  width: 36rpx;
  height: 36rpx;
  line-height: 36rpx;
  text-align: center;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.08);
  color: #666;
  font-size: 24rpx;
  z-index: 102;
  cursor: pointer;
  /* 确保按钮在内容上方 */
  pointer-events: auto;
}

/* 下拉结果容器 */
.search-results {
  width: 100%;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 6rpx 18rpx rgba(0, 0, 0, 0.12);
  max-height: 400rpx;
  overflow-y: auto;
  box-sizing: border-box;
  padding: 5rpx 0;
  /* 为关闭按钮预留空间 */
  padding-right: 50rpx;
}

/* 结果项样式 */
.result-item {
  padding: 22rpx 30rpx;
  border-bottom: 1rpx solid #f5f5f5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  transition: background-color 0.2s;
}

.result-item:last-child {
  border-bottom: none;
}

.result-item:active {
  background-color: #f0f5ff;
}

.result-name {
  font-size: 28rpx;
  color: #333;
  flex: 1;
}

.result-id {
  font-size: 24rpx;
  color: #999;
  margin: 0 15rpx;
  white-space: nowrap;
}

.result-status {
  padding: 5rpx 15rpx;
  border-radius: 15rpx;
  font-size: 22rpx;
  white-space: nowrap;
}

.status-online {
  background-color: #e8f5e9;
  color: #43a047;
}

.status-offline {
  background-color: #ffebee;
  color: #e53935;
}

/* 无结果提示（为关闭按钮预留空间） */
.no-results {
  width: 100%;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 6rpx 18rpx rgba(0, 0, 0, 0.12);
  padding: 35rpx 30rpx;
  padding-right: 50rpx;
  /* 为关闭按钮预留空间 */
  text-align: center;
  color: #999;
  font-size: 28rpx;
  box-sizing: border-box;
  position: relative;
}

/* 搜索输入框样式 */
.search-input-wrapper {
  display: flex;
  align-items: center;
  background: #f5f7fa;
  border-radius: 60rpx;
  padding: 18rpx 25rpx;
  transition: box-shadow 0.2s;
}

.search-input-wrapper:focus-within {
  box-shadow: 0 2rpx 8rpx rgba(78, 148, 225, 0.2);
}

.search-icon {
  font-size: 32rpx;
  color: #999;
  margin-right: 15rpx;
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  line-height: 40rpx;
  color: #333;
  min-height: 40rpx;
  background: transparent;
  border: none;
  outline: none;
}

.clear-icon {
  font-size: 36rpx;
  color: #999;
  margin-left: 15rpx;
  padding: 5rpx;
  cursor: pointer;
}

/* 地图容器样式 */
.map-container {
  flex: 1;
  width: 100%;
  position: relative;
  z-index: 1;
  overflow: hidden;
}

/* 信息卡片样式 */
.info-card {
  background-color: #fff;
  padding: 20rpx;
  box-shadow: 0 -2rpx 15rpx rgba(0, 0, 0, 0.1);
  z-index: 10;
  width: 100%;
  box-sizing: border-box;
  max-height: 400rpx;
  transition: opacity 0.3s ease;
  position: relative;
  /* 关键：添加相对定位 */
}

/* 信息框关闭按钮（修复显示问题） */
.info-card-close-btn {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  width: 40rpx;
  height: 40rpx;
  line-height: 40rpx;
  text-align: center;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.1);
  color: #666;
  font-size: 28rpx;
  z-index: 11;
  /* 确保在卡片内容上方 */
  cursor: pointer;
}

.card-wrapper {
  display: flex;
  border-radius: 16rpx;
  overflow: hidden;
  background-color: #fff;
  border: 1rpx solid #f0f0f0;
  /* 移除relative定位，避免影响关闭按钮 */
}

.card-image {
  width: 240rpx;
  padding: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f9f9f9;
}

.device-img {
  width: 180rpx;
  height: 180rpx;
  object-fit: contain;
}

.card-info {
  flex: 1;
  padding: 25rpx;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.device-title {
  font-size: 34rpx;
  font-weight: bold;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 400rpx;
}

.device-status {
  padding: 8rpx 20rpx;
  margin-right: 10px;
  border-radius: 20rpx;
  font-size: 24rpx;
  font-weight: 500;
}

/* 信息网格 */
.info-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 15rpx;
  margin-bottom: 20rpx;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 8rpx 0;
  border-bottom: 1rpx dashed #f0f0f0;
}

.coordinate-item .item-value {
  font-family: monospace;
}

.coordinate-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.item-label {
  font-size: 28rpx;
  color: #666;
  flex-shrink: 0;
}

.item-value {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  text-align: right;
  word-break: break-all;
}

/* 操作按钮区域 */
.card-actions {
  margin-top: 15rpx;
  display: flex;
  gap: 15rpx;
}

.detail-btn,
.navigate-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 12rpx;
  font-size: 30rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.detail-btn {
  background-color: #4e94e1;
  color: #fff;
}

.detail-btn:disabled {
  background-color: #cccccc;
  color: #ffffff;
}

.navigate-btn {
  background-color: #2ecc71;
  color: #fff;
}

.navigate-btn:disabled {
  background-color: #cccccc;
  color: #ffffff;
}
</style>
